<template>
  <div class="EditorTool">
    <!-- <el-button type="primary" @click="getHtml">获取HTML</el-button> -->
    <div style="border: 1px solid #ccc;">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 65vh; overflow-y: hidden;"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onChange="onChange"
        @onDestroyed="onDestroyed"
        @onFocus="onFocus"
        @onBlur="onBlur"
        @customAlert="customAlert"
        @customPaste="customPaste"
        @onMaxLength="onMaxLength"
      />
    </div>
  </div>
</template>

<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { uploadImg } from "@/api/configApi.js";
export default {
  name: "EditorTool",
  components: { Editor, Toolbar },
  data() {
    let _this = this;
    return {
      editor: null,
      //   html: "<p>hello</p>",
      html: "",
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadVideo: {
            async customUpload(file, insertFn) {
              let size = file.size / 1024 / 1024;
              
              if (size > 30) {
                _this.$message.error("视频大小不能超过20M!");
                return false;
              }
              const loading = _this.$loading({
                lock: true,
                text: "上传中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
              });
              let result = await uploadImg(file);
              loading.close();
              if (result.code == 200) {
                // 自己实现上传，并得到图片 url alt href
                // 最后插入图片
                insertFn(result.data.url);
              } else {
                return false;
              }
            }
          },
          uploadImage: {
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 50 * 1024, // 50kb以下的图片采用base64
            allowedFileTypes: ["image/*"],
            maxNumberOfFiles: 1,
            // maxFileSize: 5 * 1024 // 1M
            async customUpload(file, insertFn) {
              const loading = _this.$loading({
                lock: true,
                text: "上传中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
              });
              let result = await uploadImg(file);
              loading.close();
              if (result.code == 200) {
                // 自己实现上传，并得到图片 url alt href
                // 最后插入图片
                insertFn(result.data.url);
              } else {
                return false;
              }
            },
            // 上传之前触发
            onBeforeUpload(file) {
              // onBeforeUpload(file) {    // JS 语法
              // file 选中的文件，格式如 { key: file }
              //   return false;
              return file;
            },
            // 单个文件上传失败
            onFailed(file, res) {
              // JS 语法
              console.log(`${file.name} 上传失败`, res);
            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              // JS 语法
              console.log(`${file.name} 上传出错`, err, res);
              return false;
            }
          }
        }
      },
      mode: "default" // or 'simple'
    };
  },
  mounted() {
    // this.$message.success('富文本初始化完成');
    // setTimeout(() => {
    //   this.html = "<p>模拟 Ajax 异步设置内容 HTML</p>";
    // }, 1500);
    this.initial();
  },
  methods: {
    async initial() {},
    getHtml() {
      let html = this.editor.getHtml();
      return html;
    },
    setHtml(html) {
      this.editor.setHtml(html);
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
      window.editor = this.editor;
      // console.log("onCreated", editor);
    },
    onChange(editor) {
      // console.log("onChange", editor.children);
    },
    onDestroyed(editor) {
      // console.log("onDestroyed", editor);
    },
    onMaxLength(editor) {
      // console.log("onMaxLength", editor);
    },
    onFocus(editor) {
      // console.log("onFocus", editor);
    },
    onBlur(editor) {
      // console.log("onBlur", editor);
    },
    customAlert(info, type) {
      // window.alert(`customAlert in Vue demo\n${type}:\n${info}`);
    },
    customPaste(editor, event, callback) {
      callback(true);
      return;
      console.log("ClipboardEvent 粘贴事件对象", event);
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 自定义插入内容
      editor.insertText("xxx");

      // 返回 false ，阻止默认粘贴行为
      event.preventDefault();
      callback(false); // 返回值（注意，vue 事件的返回值，不能用 return）

      // 返回 true ，继续默认的粘贴行为
      //   callback(true)
    }
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.EditorTool {
  height: 100%;
}
</style>
